﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.Security;


using System.Net;


using System.Configuration;
using TestPetaPoco.Models;

namespace TestPetaPoco.Common
{
    /// <summary>
    /// 模拟登录用户， 将替换
    /// </summary>
    public static class LoginedUser
    {
        public static UserInfo Member { get; set; }
    }

    public static class MemberContext2
    {
        //private static string SESSION_USER_KEY = "LoginedUser";
        public const string COOKIE_EMAIL_KEY = "EWS_USER_Email";
        //private static string COOKIE_STORAGE_KEY = "Storages";

        private static IUserInfoService _UserInfoService;
        static MemberContext2()
        {
            //todo 改一下
            if (_UserInfoService == null)
                _UserInfoService =new UserInfoService();
        }

        /// <summary>
        /// 登录url地址
        /// </summary>
        public static string LoginUrl
        {
            get { return FormsAuthentication.LoginUrl; }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="rememberMe"></param>
        /// <returns>登录状态</returns>
        public static LoginStatus Login(HttpContextBase context, string userName, string password, bool rememberMe)
        {
            UserInfo user = null;
           // UserInfo user =null _UserInfoService.GetUserByEmail(userName);
            if (user == null)
            {
                return LoginStatus.UserNameNoExist;
            }
            //if (MemberEncrypt.EncryptPassWord(password) != user.Password && AESHelper.Encrypt(MemberEncrypt.EncryptPassWord(password), ConfigurationManager.AppSettings["AES_KEY"]) != user.NewPassword)
            //{
            //    return LoginStatus.PasswordError;
            //}
            //验证通过
            SaveLoginUser(context, user, rememberMe);
            return LoginStatus.Success;
        }



        /// <summary>
        /// 保存用户票据和Session
        /// </summary>
        /// <param name="context"></param>
        /// <param name="user"></param>
        /// <param name="rememberMe"></param>
        public static void SaveLoginUser(HttpContextBase context, UserInfo user, bool rememberMe)
        {
            #region Obsolete

            //var storages = user.Storages;
            //user.Storages = null;
            //string userDate = JsonHelper.SerializeObject(user);
            //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            //    1,
            //    user.Email,
            //    DateTime.Now,
            //    rememberMe ? DateTime.Now.AddDays(7) : DateTime.Now.AddHours(1),
            //    false,
            //    userDate
            //    );
            //string encTicket = FormsAuthentication.Encrypt(ticket);
            //HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            //if (rememberMe)
            //{
            //    cookie.Expires = DateTime.Now.AddDays(7);
            //}
            //cookie.Path = FormsAuthentication.FormsCookiePath;
            //cookie.Secure = FormsAuthentication.RequireSSL;
            //cookie.Domain = FormsAuthentication.CookieDomain;
            //context.Response.Cookies.Add(cookie);

            //user.Storages = storages;
            #endregion

            //保存缓存
           // _UserInfoService.SaveLoginedMember(user);

            //保存Cookie
            var emailData = MemberEncrypt.UserEncrypt(user.Email, user.Password);
            HttpCookie cookie = new HttpCookie(COOKIE_EMAIL_KEY);
            cookie.Path = FormsAuthentication.FormsCookiePath;
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Expires = rememberMe ? DateTime.Now.AddDays(7) : DateTime.Now.AddHours(8);
            cookie.Value = emailData;
            cookie.HttpOnly = false;
            cookie.Secure = false;

            context.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public static void LoginOut()
        {
            if (UserName != null)
            {
             //   _UserInfoService.RemoveLoginedMember(UserName);
            }

            if (HttpContext.Current.Request.Cookies.AllKeys.Contains(COOKIE_EMAIL_KEY))
            {
                var cookie = new HttpCookie(COOKIE_EMAIL_KEY);
                cookie.Expires = DateTime.MinValue;

                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            FormsAuthentication.SignOut();

            //跳转到登录页面
            HttpContext.Current.Response.Redirect(LoginUrl);
        }

        #region Obsolete
        ///// <summary>
        ///// 保存Cookie
        ///// </summary>
        ///// <param name="context"></param>
        ///// <param name="key"></param>
        ///// <param name="value"></param>
        //private static void SaveCookie(HttpContextBase context, string key, string value)
        //{
        //    HttpCookie cookie = new HttpCookie(key);
        //    cookie.Path = FormsAuthentication.FormsCookiePath;
        //    cookie.Secure = FormsAuthentication.RequireSSL;
        //    cookie.Domain = FormsAuthentication.CookieDomain;
        //    cookie.Value = value;
        //    context.Response.Cookies.Add(cookie);
        //}

        ///// <summary>
        ///// 保存登录Cookie
        ///// </summary>
        ///// <param name="context"></param>
        //private static void SaveLoginCookie(HttpContextBase context, UserInfo user)
        //{
        //    var emailData = MemberEncrypt.UserEncrypt(user.Email, context.Request.UserHostAddress);
        //    SaveCookie(context, COOKIE_EMAIL_KEY, emailData);
        //}

        ///// <summary>
        ///// 移除登录Cookie
        ///// </summary>
        ///// <param name="context"></param>
        ///// <param name="key"></param>
        //private static void RemoveLoginCookie(HttpContext context)
        //{
        //    var cookieKeys = context.Request.Cookies.AllKeys;
        //    if (cookieKeys != null && cookieKeys.Length > 0)
        //    {
        //        foreach (var key in cookieKeys)
        //        {
        //            RemoveCookie(context, key);
        //        }
        //    }
        //}

        ///// <summary>
        ///// 清空指定cookie
        ///// </summary>
        ///// <param name="context"></param>
        ///// <param name="key"></param>
        //private static void RemoveCookie(HttpContext context, string key)
        //{
        //    HttpCookie cookie = new HttpCookie(key);
        //    cookie.Path = FormsAuthentication.FormsCookiePath;
        //    cookie.Secure = FormsAuthentication.RequireSSL;
        //    cookie.Domain = FormsAuthentication.CookieDomain;
        //    cookie.Expires = new DateTime(1900, 1, 1);
        //    cookie.Value = null;
        //    context.Response.Cookies.Add(cookie);
        //}
        #endregion

        //当前登录用户
        public static string UserName
        {
            get
            {
                string result = string.Empty;
                if (HttpContext.Current.Request.Cookies[COOKIE_EMAIL_KEY] != null)
                {
                    string emailEncryptData = HttpContext.Current.Request.Cookies[COOKIE_EMAIL_KEY].Value;
                    if (!string.IsNullOrEmpty(emailEncryptData))
                    {
                        var keyValue = MemberEncrypt.UserDecrypt(emailEncryptData);
                        if (keyValue.HasValue)
                        {
                            KeyValuePair<string, string> data = keyValue.Value;
                            //string currentIP = HttpContext.Current.Request.UserHostAddress;
                            //if (data.Value == currentIP)
                            {
                                result = data.Key;
                            }
                        }
                    }
                }
                return result;
            }

            //get
            //{
            //    return HttpContext.Current.User.Identity.Name;
            //}
        }


        public static UserInfo Member
        {
            get
            {
                string userName = UserName;
                if (string.IsNullOrEmpty(userName)) return null;
                UserInfo user = null;
                //var user = _UserInfoService.GetUserByEmail(userName);
                if (user != null)
                    return user;
                else
                {
                    string emailEncryptData = HttpContext.Current.Request.Cookies[COOKIE_EMAIL_KEY].Value;
                    var keyValue = MemberEncrypt.UserDecrypt(emailEncryptData);
                    if (keyValue != null)
                    {
                        user = GetMemberForCookie(keyValue.Value.Key, keyValue.Value.Value);
                    }
                    if (user == null) return null;
                 //   _UserInfoService.SaveLoginedMember(user);
                    return user;
                }
            }
        }

        //根据保存的票据获取用户信息
        private static UserInfo GetMemberForCookie(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName)) return null;

            //var keyValue = MemberEncrypt.UserDecrypt(userName);
            //if (keyValue == null) return null;

            //if (string.IsNullOrEmpty(keyValue.Value.Key)) return null;
            //if (keyValue.Value.Value != HttpContext.Current.Request.UserHostAddress) return null;

            //string email = keyValue.Value.Key;

            UserInfo user = null;
            //var user = _UserInfoService.GetUserByEmail(userName);
            if (user == null) return null;
            if (password != user.NewPassword && password != user.Password) return null;

           // user.Storages = ServiceFactory.CreateFacade<IStorageService>().GetStoragesInUserByUserId(user.UserId);
            return user;

            //if (string.IsNullOrEmpty(userName))
            //    return null;

            //FormsIdentity ident = HttpContext.Current.User.Identity as FormsIdentity;
            //FormsAuthenticationTicket ticket = ident.Ticket;
            //var user = JsonHelper.DeserializeObject<UserInfo>(ticket.UserData);

            //user.Storages = ServiceFactory.CreateFacade<IStorageService>().GetStoragesByProcessCenter(user.ProcessCenterId);
            //return user;
        }
    }
}